package com.ruoyi.system.service.shopping.impl;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.shopping.Address;
import com.ruoyi.system.domain.shopping.Order;
import com.ruoyi.system.domain.shopping.OrderDtl;
import com.ruoyi.system.domain.shopping.ShoppingCart;
import com.ruoyi.system.domain.shopping.vo.OrderVo;
import com.ruoyi.system.mapper.shopping.AddressMapper;
import com.ruoyi.system.mapper.shopping.OrderMapper;
import com.ruoyi.system.mapper.shopping.ShoppingCartMapper;
import com.ruoyi.system.service.shopping.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public List<Order> selectOrderList(Integer userId) {
        List<Order> orders = orderMapper.selectOrderList(userId);
        return orders;
    }

    @Override
    public List<OrderVo> selectOrderVoList(Integer userId,String username) {
        return orderMapper.selectOrderVoList(userId,username);
    }

    @Override
    public Boolean create(Integer userId, Integer addressId, Integer[] shoppingCartIds) {
        //查询地址是否存在
        Address address = addressMapper.selectAddress(addressId);
        if (address != null) {
            if (address.getUserId() == userId) {
                //新增order
                UUID uuid = UUID.randomUUID();
                Order order = new Order();
                order.setUserId(userId);
                order.setOrderNum(uuid.toString());
                order.setOrderTime(LocalDateTime.now());
                order.setAddressee(address.getName());
                order.setAddressDtl(address.getAddressDtl());
                order.setAddresseeArea(address.getArea());
                order.setAddressTags(address.getAddressTags());
                order.setAddresseePhone(address.getPhone());
                orderMapper.insert(order);
                //新增order_dtl
                List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectListByIds(shoppingCartIds);
                for (ShoppingCart shoppingCart : shoppingCarts) {
                    OrderDtl orderDtl = new OrderDtl();
                    BeanUtils.copyProperties(shoppingCart,orderDtl);
                    orderDtl.setOrderId(order.getOrderId());
                    orderMapper.insertDtl(orderDtl);
                }
                //删除购物车
                int i = shoppingCartMapper.deleteByIds(shoppingCartIds);
                return i>0;
            }
        }
        return false;
    }
}
